package com.siblings.loan.ui.steps.act

import android.annotation.SuppressLint
import android.app.Activity
import android.graphics.Color
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import com.lib.base.utils.log.LogHelper
import com.siblings.loan.R
import com.siblings.loan.databinding.ActStepsBinding
import com.siblings.loan.databinding.ItemStepTitleBinding
import com.siblings.loan.http.HttpHelper
import com.siblings.loan.ui.steps.impl.SibStepsPresenterImpl
import com.siblings.loan.ui.steps.view.ISibStepsView
import com.siblings.loan.ui.steps.view.SibStepAccountView
import com.siblings.loan.ui.steps.view.SibStepCommonView
import com.siblings.loan.ui.steps.view.SibStepContactView
import com.siblings.loan.ui.steps.view.SibStepOcrView
import com.siblings.loan.ui.steps.view.SibStepSelfieView
import com.siblings.loan.utils.dialog.KefuDialog
import com.siblings.loan.utils.dialog.TipsDialog
import com.siblings.loan.utils.event.SibEventData
import com.siblings.loan.utils.event.SibEventType
import com.siblings.loan.utils.imagecovert.ImageConvert
import com.siblings.mvp.MvpAct
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject

/**
 * SiblingsLoan
 * @Author wwdeng
 * @CreateTime: 2024/7/10 11:17
 * @Annotation：认证流程
 */
class SibStepsAct: MvpAct<ISibStepsView,SibStepsPresenterImpl>(),ISibStepsView {

    lateinit var binding: ActStepsBinding
    private var stepContentLayout: FrameLayout? = null
    //图片选择
    lateinit var pickMedia: ActivityResultLauncher<PickVisualMediaRequest>

    //联系人
    private var contactView: SibStepContactView? = null
    //OcrView
    private var ocrView: SibStepOcrView? = null
    //SelfieView
    private var selfieView: SibStepSelfieView? = null
    //账号绑定
    private var accountView: SibStepAccountView? = null

    override fun createMvpPresenter(): SibStepsPresenterImpl {
        return SibStepsPresenterImpl(this)
    }

    override fun getSibRootView(): View {
        binding = ActStepsBinding.inflate(layoutInflater)
        return binding.root
    }
    override fun initSibView() {
        setSibTitleBarVisibility(View.VISIBLE)
        setSibTitleBarColor(Color.parseColor("#FFFFFF"))
        setSibTextTitle(getString(R.string.steps_title))
        setSibTextTitleGravity(Gravity.CENTER)
        setSibBackBtnRes(R.mipmap.pic_back_theme)
        setSibRightBtnRes(R.mipmap.pic_kefu_theme)

        EventBus.getDefault().register(this)
    }
    override fun initSibListener() {
        //联系客服
        rootViewBinding.ivFun.setOnClickListener {
            showSibKefuDialog("Information Step Page")
            HttpHelper.addSibEventAction(SibEventType.CLICK.SIB_CLICK_CUSTOMER, "Information Step Page")
        }

        //继续
        binding.btnContinuer.setOnClickListener {
            HttpHelper.addSibEventAction(SibEventType.CLICK.SIB_CLICK_STEP_CHECK_WAIT_CONTINUER,"")
            onIntent(SibStepCheckWaitAct::class.java)
            finish()
        }

        // 1-注册图库组件
        pickMedia = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
            if (uri != null) {
                // 图片处理
                ImageConvert.covert(context = this, uri = uri) { localPath, bitmap ->
                    if (localPath != null){
                        LogHelper.e(">>>>>>>album>>>>>>>>>>$localPath")
                        showSibLoading(isTOuchOut = false, isCancel = false)
                        mvpPresenter.onSibUploadImageAction(localPath)
                    }
                }
            } else {
                LogHelper.e("No media selected")
            }
        }
    }

    override fun initSibData() {
        mvpPresenter.loadSibProcessStepAction()
    }

    /**
     * 移除所有Step
     */
    override fun removeSibStepAllViews() {
        binding.selfieTipsLayout.visibility = View.GONE
        binding.btnContinuer.visibility = View.GONE
        binding.stepsLayout.removeAllViews()
    }

    /**
     * 添加已完成View
     */
    @SuppressLint("SetTextI18n")
    override fun addSibStepAfterView(item: JSONObject) {
        val itemView = ItemStepTitleBinding.inflate(layoutInflater)
        itemView.textStepTitle.text = item.optString("stepTitle")
        itemView.textStepIndex.text = "${item.optInt("selectIndex") + 1}/${item.optString("itemCount")}"

        itemView.stepLayout.setBackgroundColor(Color.parseColor("#FF4DB673"))
        itemView.textStepTitle.setTextColor(Color.parseColor("#FFFFFFFF"))
        itemView.imgStepStatus.setImageResource(R.mipmap.pic_step_after)
        itemView.imgStepStatus.visibility = View.VISIBLE
        itemView.textStepIndex.visibility = View.GONE
        itemView.stepContentLayout.visibility = View.GONE

        binding.stepsLayout.addView(itemView.root)
    }

    /**
     * 添加未开始Step
     */
    @SuppressLint("SetTextI18n")
    override fun addSibStepBeforeView(item: JSONObject) {
        val itemView = ItemStepTitleBinding.inflate(layoutInflater)
        itemView.textStepTitle.text = item.optString("stepTitle")
        itemView.textStepIndex.text = "${item.optInt("selectIndex") + 1}/${item.optString("itemCount")}"

        itemView.stepLayout.setBackgroundColor(Color.parseColor("#FFF9F9F9"))
        itemView.textStepTitle.setTextColor(Color.parseColor("#FFA5AABE"))
        itemView.imgStepStatus.setImageResource(R.mipmap.pic_step_before)
        itemView.imgStepStatus.visibility = View.VISIBLE
        itemView.textStepIndex.visibility = View.GONE
        itemView.stepContentLayout.visibility = View.GONE

        binding.stepsLayout.addView(itemView.root)
    }

    /**
     * 添加当前进行中Step
     */
    @SuppressLint("SetTextI18n", "CommitTransaction")
    override fun addSibStepCurrentView(item: JSONObject) {
        val itemView = ItemStepTitleBinding.inflate(layoutInflater)
        itemView.textStepTitle.text = item.optString("stepTitle")
        itemView.textStepIndex.text = "${item.optInt("selectIndex") + 1}/${item.optString("itemCount")}"

        itemView.stepLayout.setBackgroundColor(Color.parseColor("#FFFFFFFF"))
        itemView.textStepTitle.setTextColor(Color.parseColor("#FF4DB673"))
        itemView.imgStepStatus.visibility = View.GONE
        itemView.textStepIndex.visibility = View.VISIBLE
        itemView.stepContentLayout.visibility = View.VISIBLE

        stepContentLayout = itemView.stepContentLayout
        binding.stepsLayout.addView(itemView.root)
        HttpHelper.addSibEventAction(String.format(SibEventType.PAGE.SIB_PAGE_STEP_COMMON_XX_START,item.optString("stepTitle")),"")

//        binding.nestedScrollView.post {
//            val scollY = curtStepViewBinding.textStepTitle.y
//            LogHelper.e("scollY>>>>>>>>>>>>>>>>>>>>>$scollY")
//            binding.nestedScrollView.scrollTo(0,100)
//        }
    }

    /**
     * 所有步骤已完成
     */
    override fun showSibLoanAppalyPage() {
        binding.btnContinuer.visibility = View.VISIBLE
    }

    /**
     * Contact 信息
     */
    override fun showSibStepContactPage(stepItem: JSONObject,contactList: ArrayList<JSONObject>) {
        if (contactView == null){
            contactView = SibStepContactView(this,stepItem)
        }
        contactView!!.setSibContactListData(contactList)
        val viewRoot = contactView!!.includeSibStepContactView()
        val viewParent = viewRoot.parent
        if (viewParent != null){
            (viewParent as ViewGroup).removeView(viewRoot)
        }
        stepContentLayout!!.addView(viewRoot)
    }

    /**
     * Ocr 样式
     */
    override fun showSibStepOcrPage() {
        if (ocrView == null){
            ocrView = SibStepOcrView(this)
        }
        val viewRoot = ocrView!!.includeSibStepOcrView()
        val viewParent = viewRoot.parent
        if (viewParent != null){
            (viewParent as ViewGroup).removeView(viewRoot)
        }
        stepContentLayout!!.addView(viewRoot)
    }

    /**
     * Selfie 自拍照样式
     */
    override fun showSibStepSelfiePage() {
        //自拍照需要显示顶部提示
        binding.selfieTipsLayout.visibility = View.VISIBLE
        if (selfieView == null){
            selfieView = SibStepSelfieView(this)
        }
        val viewRoot = selfieView!!.includeSibStepSelfieView()
        val viewParent = viewRoot.parent
        if (viewParent != null){
            (viewParent as ViewGroup).removeView(viewRoot)
        }
        stepContentLayout!!.addView(viewRoot)
    }

    /**
     * 账户绑定样式（法语地区）
     */
    override fun showSibStepAccountPage() {
        if (accountView == null){
            accountView = SibStepAccountView(this)
        }
        val viewRoot = accountView!!.includeSibStepAccountView()
        val viewParent = viewRoot.parent
        if (viewParent != null){
            (viewParent as ViewGroup).removeView(viewRoot)
        }
        stepContentLayout!!.addView(viewRoot)
        mvpPresenter.loadSibAccountListAction()
    }

    /**
     * 常规通用样式
     */
    override fun showSibStepCommonPage(stepItem: JSONObject,dataList: ArrayList<JSONObject>) {
        val commonStepView = SibStepCommonView(this,stepItem)
        commonStepView.setSibCommonData(dataList)
        stepContentLayout!!.addView(commonStepView.includeSibStepCommonView())
    }

    /**
     * 图片上传成功
     */
    override fun showSibUploadImageSuccess(imgPath: String, imgUrl: String) {
        //Ocr 相册选择照片
        if (ocrView != null){
            ocrView!!.showSibSelectImags(imgPath,imgUrl)
        }
    }

    /**
     * 设置已绑定账户列表
     */
    override fun showSibAccountList(accountList: ArrayList<JSONObject>) {
        if (accountView != null){
            accountView!!.setSibAccountListData(accountList)
        }
    }

    /**
     * 流程提交成功
     * 需要发送通知刷新总流程
     */
    override fun showSibSubmitSuccess() {
        //通知刷新总流程
        EventBus.getDefault().post(SibEventData(SibEventData.TYPE.SIB_PROCESS_REFRESH))
    }

    /**
     * Ocr拍照
     */
    val takePhotoResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        when (result.resultCode) {
            Activity.RESULT_OK -> {
                LogHelper.e(">>>>>>onActivityResult: data = " + result.data)
                val imgLocalPath = result.data!!.getStringExtra("imgLocalPath").toString()
                val imgUrl = result.data!!.getStringExtra("imgUrl").toString()
                if (ocrView != null){
                    ocrView!!.showSibSelectImags(imgLocalPath,imgUrl)
                }
            }
        }
    }

    /**
     * 人脸拍照
     */
    val faceCameraResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        when (result.resultCode) {
            RESULT_OK -> {
                val faceImgPath = result.data!!.getStringExtra("imgLocalPath").toString()
                LogHelper.e(">>>>>>>>>face info ：$faceImgPath")
                val imgLocalPath = result.data!!.getStringExtra("imgLocalPath").toString()
                val imgUrl = result.data!!.getStringExtra("imgUrl").toString()
                if (selfieView != null){
                    selfieView!!.showSibSelfieAfterView(imgLocalPath,imgUrl)
                }

            }
        }
    }

    /**
     * 信息填写不完整提示
     */
    fun showSibTipsDialog(eventRemark: String){
        val tipsDialog = TipsDialog(this,eventRemark,object : TipsDialog.IDialogCallback{
            override fun onClick(view: View?) {
                when(view!!.id){
                    R.id.btnOk -> {
                        HttpHelper.addSibEventAction(SibEventType.CLICK.SIB_CLICK_DIALOG_TIPS_OK,eventRemark)
                    }
                }
            }
        })
        tipsDialog.setCancelable(true)
        tipsDialog.setCanceledOnTouchOutside(false)
        tipsDialog.show()
        tipsDialog.hideSibBtnCancel()
        tipsDialog.setTipsTitle(getString(R.string.tips))
        tipsDialog.setTips(getString(R.string.tips_submit_error))
    }

    /**
     * 显示客服dialog
     */
    private fun showSibKefuDialog(eventRemark: String){
        val kefuDialog = KefuDialog(this,eventRemark,object : KefuDialog.IDialogCallback{
            override fun onClick(view: View?) {
            }
        })
        kefuDialog.setCancelable(true)
        kefuDialog.setCanceledOnTouchOutside(true)
        kefuDialog.show()
    }

    /**
     * 提示绑定另一个渠道账户
     */
    override fun showSibBingAccountOtherDialog(otherInfo: JSONObject) {
        if (accountView != null){
            accountView!!.showSibBingAccountOtherDialog(otherInfo)
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    fun onRefreshedProcess(event: SibEventData){
        if(event.eventType == SibEventData.TYPE.SIB_PROCESS_REFRESHED){//总流程刷新完成
            mvpPresenter.loadSibProcessStepAction()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        if (contactView != null){
            contactView!!.onDestroy()
            contactView = null
        }
        if (ocrView != null){
            ocrView!!.onDestroy()
            ocrView = null
        }
        if (selfieView != null){
            selfieView!!.onDestroy()
            selfieView = null
        }
    }
}